package MyQueue;

//设计循环队列  https://leetcode.cn/problems/design-circular-queue/description/
class MyCircularQueue {
    private int[] arr;
    private int front;//队头
    private int rear;//队尾

    public MyCircularQueue(int k) {
        //浪费有一个空间，而题目没有浪费，故k+1
        arr = new int[k+1];
    }
    
    public boolean enQueue(int value) {
        if (isFull()) {
            return false;
        }
        arr[rear] = value;
        rear = (rear + 1) % arr.length;
        return true;
    }
    
    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        front = (front + 1) % arr.length;
        return true;
    }
    
    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        int val = arr[front];
        return val;
    }
    
    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        //rear始终指向存有数据的下一个内存空间，获取队尾元素需要rear的上一个下标
        int val = rear == 0? arr[arr.length - 1] : arr[rear - 1];
        return val;
    }
    
    public boolean isEmpty() {
        return front == rear;
    }
    
    public boolean isFull() {
        //浪费一个空间的判满规则
        return (rear+1)%arr.length == front;
    }
}